//
//  RYMessageManager.m
//  LinYa
//
//  Created by 初程程 on 2018/3/21.
//  Copyright © 2018年 初程程. All rights reserved.
//

#import "RYMessageManager.h"
#import <RongIMLib/RongIMLib.h>
#import <RongIMKit/RongIMKit.h>
#import "YLCTabBarViewController.h"
#import "AppDelegate.h"
@interface RYMessageManager()<RCIMReceiveMessageDelegate,RCIMUserInfoDataSource>
@property (nonatomic ,copy)NSString *userId;
@end
@implementation RYMessageManager
{
    NSString *userName;
    NSString *userIconPath;
}
+ (RYMessageManager *)shareManager{
    static RYMessageManager *shareMessage;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareMessage = [[RYMessageManager alloc] init];
    });
    return shareMessage;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.messageSignal = [RACSubject subject];
        self.loginSuccessSignal = [RACSubject subject];
        [RCIM sharedRCIM].userInfoDataSource = self;
    }
    return self;
}
- (void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *))completion{
    YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
    
    if ([userModel.user_id isEqualToString:userId]) {
        return completion([[RCUserInfo alloc] initWithUserId:userId name:userName portrait:userIconPath]);
    }else{
        YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
        
        [YLCNetWorking loadNetServiceWithParam:@{@"myId":userModel.user_id,@"token":userModel.token,@"userId":userId} method:@"POST" urlPath:@"app/user/baseDetail" delegate:self response:^(id responseObject, NSError *error) {
            if (error) {
                return ;
            }
            completion([[RCUserInfo alloc] initWithUserId:userId name:responseObject[@"nick_name"] portrait:responseObject[@"imgsrc"]]);
        }];
    }
}
- (void)observerMessage{
    [[RCIM sharedRCIM] setReceiveMessageDelegate:self];
}
- (void)onRCIMReceiveMessage:(RCMessage *)message left:(int)left{
    [self.messageSignal sendNext:message];
}
//初始化
- (void)commonInitIMLib{
    
    [[RCIM sharedRCIM] initWithAppKey:RongYunKey];
}
//获取测试token
- (void)getTestToken{
    
}
- (int)getUnreadCount{
    int count = [[RCIMClient sharedRCIMClient] getUnreadCount:@[@(ConversationType_PRIVATE)]];
//    int count = [[RCIMClient sharedRCIMClient] getTotalUnreadCount];
    return count;
}
- (void)rongyunLogin{
    
    YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
    
    if ([YLCFactory isStringOk:userModel.user_id]&&[YLCFactory isStringOk:userModel.token]) {
        [YLCNetWorking loadNetServiceWithParam:@{@"userId":userModel.user_id,@"token":userModel.token} method:@"POST" urlPath:@"app/public/getRongToken" delegate:self response:^(id responseObject, NSError *error) {
            if (error) {
                return ;
            }
            
            userName = responseObject[@"nick_name"];
            userIconPath = responseObject[@"imgsrc"];
            [self loginConnectWithToken:responseObject[@"token"]];
        }];
    }
}
//连接消息服务器
- (void)loginConnectWithToken:(NSString *)token
{
    [[RCIMClient sharedRCIMClient] connectWithToken:token success:^(NSString *userId) {
        NSLog(@"登录成功userid为%@",userId);
        dispatch_async(dispatch_get_main_queue(), ^{
            [YLCAccountManager shareManager].hasLoginRY = YES;
            
            YLCTabBarViewController *con = (YLCTabBarViewController *)[AppDelegate appDelegate].window.rootViewController;
            [con hiddenRed];
            [self.loginSuccessSignal sendNext:@""];
        });
        [RCIM sharedRCIM].enableMessageAttachUserInfo = YES;

        [RCIM sharedRCIM].currentUserInfo = [[RCUserInfo alloc] initWithUserId:userId name:userName portrait:userIconPath];
    } error:^(RCConnectErrorCode status) {
        NSLog(@"消息错误码为 %ld",(long)status);
        if (status==RC_CONN_ID_REJECT) {
            NSLog(@"appkey 错误");
        }
        if (status==RC_CONN_TOKEN_INCORRECT) {
            NSLog(@"token 过期");
        }
        if (status==RC_CONN_NOT_AUTHRORIZED) {
            NSLog(@"appkey与token 不一致");
        }
    } tokenIncorrect:^{
        NSLog(@"token过期或者不正确");
    }];
}
@end
